package com.lh.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lh.core.BusinessException;
import com.lh.entity.table.DeadLineNodeRecord;
import com.lh.entity.table.DeadlineNode;
import com.lh.entity.table.DeadlineNodeUpdate;
import com.lh.mapper.DeadLineNodeRecordMapper;
import com.lh.mapper.DeadlineNodeMapper;
import com.lh.mapper.DeadlineNodeUpdateMapper;
import com.lh.service.DeadLineNodeRecordService;
import com.lh.service.DeadlineNodeUpdateServer;
import com.lh.utils.Answer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import javax.xml.transform.Result;
import java.util.Date;
import java.util.List;

@Service
public class DeadlineNodeUpdateServiceImpl implements DeadlineNodeUpdateServer {


    @Resource
    private DeadlineNodeMapper deadlineNodeMapper;

    @Resource
    private DeadlineNodeUpdateMapper deadlineNodeUpdateMapper;

    @Resource
    private DeadLineNodeRecordMapper deadLineNodeRecordMapper;


    @Override
    public int submitProgressUpdate(DeadlineNodeUpdate deadlineNodeUpdate) {
        // 1. 校验节点是否存在
        DeadlineNode node = deadlineNodeMapper.selectById(Integer.valueOf(deadlineNodeUpdate.getNodeId()));
        if (node == null) {
            return 0;
        }
        deadlineNodeUpdate.setOldProgress(node.getProgress());
        deadlineNodeUpdate.setOldProcess(node.getProcess());
        deadlineNodeUpdate.setOldState(node.getState());
        deadlineNodeUpdate.setOldEndTime(node.getEndTime());
        deadlineNodeUpdate.setOldRemark(node.getRemark());
        deadlineNodeUpdate.setCreatedTime(new Date());
        int result = deadlineNodeUpdateMapper.insert(deadlineNodeUpdate);
        return result;
    }


    /**
     * 处理节点修改审核
     * @param deadNodeId 修改记录ID
     * @param approvalStatus 审核状态（通过/不通过）
     * @param approvalReason 审核原因
     * @return 处理结果
     */
    @Override
    @Transactional
    public int handleNodeUpdateApproval(Integer id,String deadNodeId, String approvalStatus,
                                           String approvalReason) {
        // 1. 查询修改记录
        DeadlineNodeUpdate updateRecord = deadlineNodeUpdateMapper.selectById(id);
        if (updateRecord == null) {
            return 0;
        }

        // 2. 检查记录是否已审核
        if (updateRecord.getApprovalStatus() != null &&
                !"".equals(updateRecord.getApprovalStatus().trim())) {
            return 0;
        }

        // 3. 更新审核信息
        updateRecord.setApprovalStatus(approvalStatus);
        updateRecord.setApprovalReason(approvalReason);
        updateRecord.setSignTime(new Date());
        deadlineNodeUpdateMapper.updateById(updateRecord);

        // 4. 如果审核通过，则更新节点信息
        if ("approved".equals(approvalStatus) || "1".equals(approvalStatus)) {
            // 查询对应的节点
            DeadlineNode node = deadlineNodeMapper.selectById(updateRecord.getNodeId());
            if (node == null) {
                // 回滚事务
                throw new BusinessException("节点不存在，无法更新");
            }

            // 更新节点信息（根据实际需要更新的字段进行设置）
            node.setRemark(updateRecord.getNewRemark());
            node.setEndTime(updateRecord.getNewEndTime());
            node.setProgress(updateRecord.getNewProgress());
            node.setUpdateTime(new Date());
            node.setProcess(updateRecord.getNewProcess());

            DeadLineNodeRecord deadLineNodeRecord = new DeadLineNodeRecord();
            deadLineNodeRecord.setRemark(updateRecord.getNewRemark());
            deadLineNodeRecord.setNodeId(Integer.valueOf(updateRecord.getNodeId()));
            deadLineNodeRecord.setUpdateTime(new Date());
            deadLineNodeRecord.setFileUrl(updateRecord.getNewFileList());
            deadLineNodeRecord.setProgress(updateRecord.getNewProgress());
            deadLineNodeRecord.setEndTime(updateRecord.getNewEndTime());
            deadLineNodeRecord.setUpdateBy(updateRecord.getSignUser());
            deadLineNodeRecordMapper.insert(deadLineNodeRecord);

            // 如果有其他需要更新的字段，继续添加...
            deadlineNodeMapper.updateById(node);
        }

        return 1;
    }

    @Override
    public List<DeadlineNodeUpdate> selectLastById(Integer id) {
        List<DeadlineNodeUpdate> list = deadlineNodeUpdateMapper.selectList(new LambdaQueryWrapper<DeadlineNodeUpdate>()
                .eq(DeadlineNodeUpdate::getNodeId, id)
                .isNull(DeadlineNodeUpdate::getApprovalStatus)  // 使用isNull判断空值
                .orderByDesc(DeadlineNodeUpdate::getId));
        return list;
    }

    @Override
    public Answer<Object> selectListById(Integer id) {
        List<DeadlineNodeUpdate> list = deadlineNodeUpdateMapper.selectList(new LambdaQueryWrapper<DeadlineNodeUpdate>()
                .eq(DeadlineNodeUpdate::getNodeId, id)// 使用isNull判断空值
                .orderByDesc(DeadlineNodeUpdate::getId));
        return Answer.ok(list);
    }
}
